package cn.net.xyan.blossom.core.controller

import cn.net.xyan.blossom.kotlin.AllOpen
import cn.net.xyan.blossom.kotlin.ErrorRsp
import cn.net.xyan.blossom.kotlin.StatusAndMessageError
import cn.net.xyan.blossom.kotlin.logger
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.bind.annotation.ResponseStatus
import javax.servlet.http.HttpServletResponse

@ControllerAdvice
@AllOpen
class GlobalControllerExceptionHandler {

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)  // 500
    @ExceptionHandler(*arrayOf(StatusAndMessageError::class,Throwable::class))
    @ResponseBody
    fun handleException(e:Throwable, resp: HttpServletResponse): ErrorRsp {
        var error = e
        if ( error !is StatusAndMessageError){
            error = StatusAndMessageError(-1, e)
        }
        val err = ErrorRsp(error)
        resp.contentType = MediaType.APPLICATION_JSON_UTF8_VALUE
        logger.error(err.traceStack)
        return err
    }

}